package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.saas.domain.CTenant;
import com.ruoyi.saas.service.ICTenantService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICTenantService tenantService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 登录方法(App)
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/mobile")
    public AjaxResult mobileLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());

        SysUser loginUser = userService.selectUserByUserName(loginBody.getUsername());
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("username", loginUser.getUserName());
        tokenMap.put("password", loginUser.getPassword());
        tokenMap.put("nickname", loginUser.getNickName());
        tokenMap.put("id", loginUser.getUserId());
        tokenMap.put("icon", loginUser.getAvatar());
        tokenMap.put("email", loginUser.getEmail());
        tokenMap.put("phonenumber", loginUser.getPhonenumber());
        tokenMap.put("deptId", loginUser.getDeptId());
        tokenMap.put("sex", loginUser.getSex());
        tokenMap.put("salt", loginUser.getSalt());
        tokenMap.put("status", loginUser.getStatus());
        tokenMap.put("delFlag", loginUser.getDelFlag());
        tokenMap.put("loginIp", loginUser.getLoginIp());
        tokenMap.put("tenantCode", loginUser.getTenantCode());
        ajax.put(AjaxResult.DATA_TAG, tokenMap);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        AjaxResult ajax = AjaxResult.success();
        // 租户信息

        CTenant tenant = tenantService.selectCTenantByTenantCode(user.getTenantCode());
        if (tenant.getExpirationTime()!=null&&DateUtils.getCurrentDate().getTime() > tenant.getExpirationTime().getTime()) {
            throw new CustomException("当前企业授权已过期，请联系管理员");
        }
        ajax.put("tenant", tenant);
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);

        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUser(user);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
